package ThreadDemo;
import java.util.ArrayList;
public class WareHouse {
    //products,模拟缓冲区
    ArrayList<Integer> products = null;
    private final int MAXN = 20;
    public WareHouse(){
        products = new ArrayList<>();
    }
    public void add(int number){
        try {
            //synchronized同步
            synchronized (products) {
                if(products.size() < MAXN){
                    System.out.printf("生产者向仓库中存入了一个编号为%d商品\n", number);
                    products.add(number);
                    System.out.printf("仓库有中共有: "+ products.size() + "个商品\n");
                    products.notify();
                }else if(products.size() == MAXN){
                    System.out.println("仓库已满，请耐心等待消费者消费！！！");
                    products.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();// TODO Auto-generated catch block
        }
    }

    public void get(int number){
        try {
            //synchronized同步
            synchronized (products) {
                if(products.size() <= 0){
                    System.out.println("仓库已空，请耐心等待商品的添加！！");
                    products.wait();
                }else{
                    System.out.printf("消费者取出了编号为%d的商品\n", products.get(0));
                    products.remove(0);
                    System.out.println("仓库有中共有: "+ products.size() + "个");
                    products.notify();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
